package game.gui;

import game.code.Loader;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 * Is-A JPanel.
 * Has-A JTextArea
 * knows LetterInventory
 * handles user pressed the BACK_SPACE key on this area.
 * 
 * @author Ying
 *
 */
public class WordFormation extends JPanel {
	
	/**
	 * holds the user selected six letters to display
	 */
	private JTextArea textArea;
	/**
	 * stores the text that to be displayed
	 */
	private StringBuffer textBuffer; 
 
	public WordFormation(  ){
		super();
		 
		textArea = new JTextArea();;
		textArea.setEditable(false);
		textBuffer = new StringBuffer();
		textArea.setText(textBuffer.toString());
		
		//todo implement use click one word and remove that word.
		//textArea.addMouseListener( );
		
		
		add(textArea);
		//this.setFont(Style.textLetterFont);
		setLayout();
	}
	
	/**
	 * called by the game gui, add a keylistener to the wordFormation
	 * 's textArea. When user pressed the back_space, it will remove 
	 * last letter from the textArea, and re-enable the letterInvetory's
	 * conresposding button.
	 * @param lv
	 */
	public void addKeyListener(final LetterInventory lv){
		
		textArea.addKeyListener(new KeyListener(){

			@Override
			public void keyPressed(KeyEvent arg0) {
				if(arg0.getKeyCode() == KeyEvent.VK_BACK_SPACE){
					removeTail();
					lv.enableButton();
				}
				
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}});	
		
	}
	
	
	public void setLayout(){
		textArea.setColumns(Loader.KEYWORD_LEN);
		textArea.setFont(Style.WordFormationLetterFont);
		textArea.setBackground(Color.LIGHT_GRAY);
		
	}
	
	/**
	 * append a new letter to display. the user chose the letter by pressed one button from LetterInventory
	 * @param c
	 */
	public void append(Character c ){
		textArea.setText(textBuffer.append(c).toString());
	}
	
	/**
	 * called when user pressed the back_sapce key 
	 * will re-enable the button that has for that letter
	 * to be removed from letter-formation.
	 * if textBuffer is empty, do nothing.
	 */
	public void removeTail(){
		if(textBuffer.length()>0)
			textBuffer.deleteCharAt(textBuffer.length()-1);
		
		textArea.setText(textBuffer.toString());
	}
	
	/**
	 * clear out the textArea. re-set Stringbuffer to 0
	 */
	public void removeWord(){
		textBuffer.delete(0, textBuffer.length());
		textArea.setText(textBuffer.toString());
	}
	
	/**
	 * @return a String to pass into game.submit()
	 */
	public String getWord(){
		return textArea.getText();
	}
	

	
}
